<?php

namespace App\Services\OpenWechat;

use App\Models\OpenWechat\WechatUser;

/**
 * 开放平台微信用户仓库
 *
 * Author: lyun
 * Date: 2017/11/28
 * Created by Panxsoft.
 */
class WechatUserRepository
{
    /**
     * @var WechatUser
     */
    protected $wechat_user;

    public function __construct()
    {
        $this->wechat_user = new WechatUser();
    }

    /**
     * @param array $user_info
     * @see Mock::appUserGet()
     *
     * @return WechatUser
     */
    public function createOrUpdateWechatUserInfo(array $user_info)
    {
        /** @var WechatUser $wechat_user */
        $wechat_user = $this->wechat_user->firstOrNew([
            'openid' => $user_info['openid']
        ]);

        $info_columns = [
            'authorizer_id', 'nickname', 'language', 'headimgurl',
            'city', 'province', 'country', 'remark',
            'subscribe', 'subscribe_time', 'subscribe_scene',
        ];

        /** @var array $user_data */
        $user_data = collect($user_info)->only($info_columns)->all();

        foreach ($user_data as $key => $val) {
            $wechat_user->{$key} = $val;
        }

        $wechat_user->nickname_unicode = json_encode($user_data['nickname']);

        $wechat_user->save();

        return $wechat_user;
    }

}
